package net.wanho.advice;

import cn.hutool.http.useragent.UserAgent;
import cn.hutool.http.useragent.UserAgentUtil;
import cn.hutool.json.JSONUtil;
import net.wanho.mapper.UserInfoMapper;
import net.wanho.po.LoginLog;
import net.wanho.po.OperLog;
import net.wanho.service.LoginLogService;
import net.wanho.service.OperLogService;
import net.wanho.util.AddressUtil;
import net.wanho.util.CurrentUtil;
import net.wanho.util.ServletUtil;
import net.wanho.vo.LoginUserDTO;
import net.wanho.vo.R;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Date;

/**
 *
 * 登录日志切面
 */
@Component
@Aspect
public class LoginLogAspect {

    @Resource
    private LoginLogService loginLogService;

    @Pointcut("execution(* net.wanho.controller.LoginController.login(..))")
    public void pc() {
    }

    @Around("pc()")
    public Object around(ProceedingJoinPoint joinPoint) {
        HttpServletRequest request = ServletUtil.getRequest();

        LoginLog loginLog = new LoginLog();
        LoginUserDTO loginUserDTO = (LoginUserDTO) joinPoint.getArgs()[0];
        loginLog.setUserName(loginUserDTO.getUserCode());
        // loginLog.setIpaddr();
        // loginLog.setLoginLocation();

        UserAgent agent = UserAgentUtil.parse(request.getHeader("User-Agent"));
        loginLog.setBrowser(agent.getBrowser().getName());
        loginLog.setOs(agent.getOs().getName());
        loginLog.setLoginTime(new Date());

        try {
            // 核心业务
            R res = (R) joinPoint.proceed();
            loginLog.setStatus("0");
            loginLog.setMsg(res.getMessage());

            return res;
        } catch (Throwable e) {
            loginLog.setStatus("1");
            loginLog.setMsg(e.getMessage());
            throw new RuntimeException(e.getMessage());
        }finally {

            // 记录操作日志
            loginLogService.add(loginLog);
        }
    }

}